'''
()
'''
import lexer
import values as types
class Compiler:
    def __init__(self):
        self.lexer = lexer.Lexer()
    def load(self,filename):
        with open(filename,'r')  as fp:
            content = fp.read()
            l = self.lexer.tokenize(content)
            s = self.parse(l)
            return s
        return []
    def compile(self,s):
        l = self.lexer.tokenize(s)
        return self.parse(l)
    def parse(self,tokens):
        ast = []
        stack = []
        index = 0
        while index < len(tokens) :
            tmp = tokens[index]
            index+=1
            if tmp['type']=='RP' or tmp['type']=='right':
                lt = []
                while len(stack)>0:
                    t = stack.pop()
                    if type(t)==type({}) and (t['type']=='LP' or t['type']=='left'):
                        stack.append(lt)
                        break
                    else:
                        lt.insert(0,t)
            else:
                stack.append(tmp)
        return self.to_list(stack[0])
    def to_list(self,ast):
        ret = []
        for i in ast:
            if type(i) == type([]):
                ret.append(self.to_list(i))
            else:
                tmp = None
                if i['type'] == 'number':
                    if i["value"].find('.')>=0:
                        tmp = types.Float(float(i["value"]))
                    else:
                        tmp = types.Integer(int(i["value"]))
                elif i['type'] == 'string':
                    tmp = types.String( i["value"])
                elif i['type'] == 'char':
                    tmp = types.Char( i["value"])
                elif i['type'] == 'bool':
                    tmp = types.Bool( i["value"])
                elif i['type'] == 'symbol':
                    tmp = types.Symbol( i["value"])
                elif i['type'] == 'keyword':
                    tmp = types.Keyword( i["value"])
                ret.append(tmp)
        return ret